﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.EBS
{
    public class NamespaceEntry
    {
        public string Name { get; set; }

        public List<EventEntry> Events { get; private set; }

        public NamespaceEntry()
        {
            Events = new List<EventEntry>();
        }

        public EventEntry GetOrCreate(string name, Guid appId, string callback)
        {
            EventEntry @event = new EventEntry();

            bool isExist = false;
            for (int index = 0; index < Events.Count; index++)
            {
                if(string.Equals(Events[index].Name, name) && Events[index].AppId == appId)
                {
                    isExist = true;
                    @event = Events[index];
                    Logger.InfoToTag(Library.LogTAG, string.Format("register,app:{0},name:{1},callback:{2},exsit", appId, name, callback));
                    break;
                }
            }

            if(!isExist)
            {
                lock (this)
                {
                    for (int index = 0; index < Events.Count; index++)
                    {
                        if (string.Equals(Events[index].Name, name) && Events[index].AppId == appId)
                        {
                            isExist = true;
                            @event = Events[index];
                            break;
                        }
                    }

                    if(!isExist)
                    {
                        @event = new EventEntry();
                        @event.Name = name;
                        @event.AppId = appId;
                        @event.Callback = callback;
                        Events.Add(@event);

                        Logger.InfoToTag(Library.LogTAG, string.Format("register,app:{0},name:{1},callback:{2}, add", appId, name, callback));
                    }
                }
            }

            return @event;
        }

        public void Remove(string name, Guid appId)
        {
            lock(this)
            {
                for (int index = 0; index < Events.Count; index++)
                {
                    if(string.Equals(Events[index].Name, name) && Events[index].AppId == appId)
                    {
                        Events.RemoveAt(index);
                        break;
                    }
                }
            }
        }

        public List<EventEntry> Find(string @event)
        {
            List<EventEntry> eventEnties = new List<EventEntry>();

            for (int index = 0; index < Events.Count; index++)
            {
                if (string.Equals(Events[index].Name, @event))
                {
                    eventEnties.Add(Events[index]);
                }
            }
            return eventEnties;
        }
    }
}
